<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蓝猫 - 创建商品</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#722ED1',
                        neutral: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .btn-primary {
                @apply bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-all hover:shadow-md;
            }
            .btn-secondary {
                @apply bg-secondary text-white px-4 py-2 rounded-md hover:bg-secondary/90 transition-all hover:shadow-md;
            }
            .btn-outline {
                @apply border border-primary text-primary px-4 py-2 rounded-md hover:bg-primary/10 transition-all;
            }
            .form-input {
                @apply w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all;
            }
            .form-label {
                @apply block text-sm font-medium text-gray-700 mb-1;
            }
            .error-message {
                @apply text-red-500 text-sm mt-1 hidden;
            }
        }
    </style>
</head>
<body class="bg-white text-dark font-sans">
    <!-- 导航栏 -->
    <header id="navbar" class="fixed top-0 left-0 right-0 bg-white shadow-sm z-50 transition-all duration-300">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between h-16">
                <!-- Logo -->
                <a href="index.html" class="flex items-center space-x-2">
                    <span class="logo text-2xl font-bold text-blue-600">蓝猫</span>
                </a>
                
                <!-- 导航链接 - 桌面版 -->
                <nav class="hidden md:flex items-center space-x-8">
                    <a href="index.html" class="font-medium hover:text-primary transition-colors">首页</a>
                    <a href="#" class="font-medium hover:text-primary transition-colors">热卖商品</a>
                    <a href="#" class="font-medium text-primary border-b-2 border-primary pb-1">商品管理</a>
                    <a href="#" class="font-medium hover:text-primary transition-colors">关于我们</a>
                </nav>
                
                <!-- 用户功能区 -->
                <div class="flex items-center space-x-4">  
                    <button id="cartBtn" class="relative p-2 hover:text-primary transition-colors">
                        <i class="fa fa-shopping-cart text-xl"></i>
                        <span id="cartCount" class="absolute -top-1 -right-1 bg-secondary text-white text-xs rounded-full h-5 w-5 flex items-center justify-center transition-all">0</span>
                    </button>
                    <div id="auth-links" class="flex items-center space-x-4 hidden">
                        <a href="login.html" class="p-2 hover:text-primary transition-colors">
                            <i class="fa fa-sign-in text-xl"></i>
                        </a>
                        <a href="register.html" class="p-2 hover:text-primary transition-colors">
                            <i class="fa fa-user text-xl"></i>
                        </a>
                    </div>
                    <div id="user-info" class="flex items-center space-x-2">
                        <span class="text-sm font-medium"></span>
                        <button id="logoutBtn" class="text-sm text-gray-500 hover:text-primary transition-colors">退出</button>
                    </div>
                
                    <!-- 移动端菜单按钮 -->
                    <button id="mobileMenuBtn" class="md:hidden p-2 hover:text-primary transition-colors">
                        <i class="fa fa-bars text-xl"></i>
                    </button>                    
                </div>
            </div>
                       
            <!-- 移动端导航菜单 -->
            <div id="mobileMenu" class="md:hidden hidden bg-white border-t">
                <div class="container mx-auto px-4 py-3 space-y-3">
                    <a href="index.html" class="block py-2 font-medium hover:text-primary transition-colors">首页</a>
                    <a href="#" class="block py-2 font-medium hover:text-primary transition-colors">热卖商品</a>
                    <a href="#" class="block py-2 font-medium text-primary">商品管理</a>
                    <a href="#" class="block py-2 font-medium hover:text-primary transition-colors">关于我们</a>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="pt-16 pb-12">
        <section class="py-8 bg-gray-50">
            <div class="container mx-auto px-4">
                <div class="max-w-3xl mx-auto bg-white rounded-lg shadow-sm p-6 md:p-8">
                    <div class="mb-6">
                        <h1 class="text-2xl md:text-3xl font-bold mb-2">创建新商品</h1>
                        <p class="text-gray-500">填写以下信息添加新商品到商店</p>
                    </div>
                    
                    <form id="createProductForm" class="space-y-6">
                        <!-- 商品基本信息 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="productName" class="form-label">商品名称 <span class="text-red-500">*</span></label>
                                <input type="text" id="productName" name="name" class="form-input" required>
                                <div class="error-message" id="nameError">请输入商品名称</div>
                            </div>
                            
                            <div>
                                <label for="productPrice" class="form-label">商品价格 (¥) <span class="text-red-500">*</span></label>
                                <input type="number" id="productPrice" name="price" min="0" step="0.01" class="form-input" required>
                                <div class="error-message" id="priceError">请输入有效的价格</div>
                            </div>
                        </div>
                        
                        <div>
                            <label for="productCategory" class="form-label">商品分类 <span class="text-red-500">*</span></label>
                            <select id="productCategory" name="category" class="form-input" required>
                                <option value="">请选择分类</option>
                                <option value="电子产品">电子产品</option>
                                <option value="服装鞋帽">服装鞋帽</option>
                                <option value="家居用品">家居用品</option>
                            </select>
                            <div class="error-message" id="categoryError">请选择商品分类</div>
                        </div>
                        
                        <div>
                            <label for="productDescription" class="form-label">商品描述 <span class="text-red-500">*</span></label>
                            <textarea id="productDescription" name="description" rows="4" class="form-input" required></textarea>
                            <div class="error-message" id="descriptionError">请输入商品描述</div>
                        </div>
                        
                        <!-- 商品图片上传 -->
                        <div>
                            <label class="form-label">商品图片 <span class="text-red-500">*</span></label>
                            <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                                <div class="space-y-1 text-center">
                                    <i class="fa fa-cloud-upload text-3xl text-gray-400"></i>
                                    <div class="flex text-sm text-gray-600">
                                        <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-primary hover:text-primary/80">
                                            <span>上传图片</span>
                                            <input id="file-upload" name="image" type="file" accept="image/*" class="sr-only" required>
                                        </label>
                                        <p class="pl-1">或拖放文件</p>
                                    </div>
                                    <p class="text-xs text-gray-500">支持 PNG, JPG, GIF 格式</p>
                                </div>
                            </div>
                            <div class="error-message" id="imageError">请上传商品图片</div>
                            
                            <!-- 预览图 -->
                            <div id="imagePreviewContainer" class="mt-4 hidden">
                                <img id="imagePreview" src="" alt="预览图" class="max-h-64 object-contain rounded-md border">
                            </div>
                        </div>
                        
                        <!-- 商品评分 -->
                        <div>
                            <label class="form-label">初始评分</label>
                            <div class="flex items-center mt-1">
                                <div class="flex text-2xl text-gray-300">
                                    <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="1"></i>
                                    <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="2"></i>
                                    <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="3"></i>
                                    <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="4"></i>
                                    <i class="fa fa-star rating-star cursor-pointer hover:text-yellow-400 transition-colors" data-rating="5"></i>
                                </div>
                                <input type="hidden" id="productRating" name="rating" value="0">
                            </div>
                        </div>
                        
                        <!-- 商品评价数 -->
                        <div>
                            <label for="productReviews" class="form-label">初始评价数量</label>
                            <input type="number" id="productReviews" name="reviews" min="0" value="0" class="form-input">
                        </div>
                        
                        <!-- 表单操作按钮 -->
                        <div class="flex justify-end space-x-4 pt-4 border-t">
                            <a href="index.html" class="btn-outline">取消</a>
                            <button type="submit" class="btn-primary">
                                创建商品 <i class="fa fa-check ml-1"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white pt-12 pb-8">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 mb-12">
                <div>
                    <div class="flex items-center space-x-2 mb-4">
                        <span class="font-bold text-xl">蓝猫</span>
                    </div>
                    <p class="text-gray-400 mb-4">
                        提供优质商品和极简购物体验
                    </p>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-twitter"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-instagram"></i>
                        </a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-weixin"></i>
                        </a>
                    </div>
                </div>
                
                <div>
                    <h3 class="font-bold text-lg mb-4">快速链接</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">首页</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">热门商品</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">联系我们</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="font-bold text-lg mb-4">客户服务</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">购物指南</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">配送信息</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">常见问题</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="font-bold text-lg mb-4">联系我们</h3>
                    <ul class="space-y-2">
                        <li class="flex items-start">
                            <i class="fa fa-map-marker text-primary mt-1 mr-3"></i>
                            <span class="text-gray-400">北京市朝阳区某某街道123号</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-phone text-primary mr-3"></i>
                            <span class="text-gray-400">400-123-4567</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-envelope text-primary mr-3"></i>
                            <span class="text-gray-400">service@example.com</span>
                        </li>
                    </ul>
                </div>
            </div>
            
            <div class="border-t border-gray-800 pt-6 text-center text-gray-500 text-sm">
                <p>&copy; 2023 蓝猫购物. 保留所有权利.</p>
            </div>
        </div>
    </footer>

    <!-- 通知提示 -->
    <div id="toast" class="fixed bottom-6 right-6 bg-dark text-white px-4 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center">
        <i class="fa fa-check-circle text-secondary mr-2"></i>
        <span id="toastMessage"></span>
    </div>

    <script>
        // 全局状态
        let currentUser = null;
        let accessToken = localStorage.getItem('access_token');
        let cart = [];
        let selectedRating = 0;

        // DOM元素
        const createProductForm = document.getElementById('createProductForm');
        const fileUpload = document.getElementById('file-upload');
        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const ratingStars = document.querySelectorAll('.rating-star');
        const productRating = document.getElementById('productRating');
        const toast = document.getElementById('toast');
        const toastMessage = document.getElementById('toastMessage');
        const mobileMenuBtn = document.getElementById('mobileMenuBtn');
        const mobileMenu = document.getElementById('mobileMenu');
        const userInfo = document.getElementById('user-info');
        const logoutBtn = document.getElementById('logoutBtn');
        const cartCount = document.getElementById('cartCount');

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            setupEventListeners();
            checkAuth();
            loadCart();
        });

        // 设置事件监听器
        function setupEventListeners() {
            // 移动端菜单
            mobileMenuBtn.addEventListener('click', toggleMobileMenu);

            // 表单提交
            createProductForm.addEventListener('submit', handleFormSubmit);

            // 图片上传预览
            fileUpload.addEventListener('change', handleImageUpload);

            // 评分星星点击事件
            ratingStars.forEach(star => {
                star.addEventListener('click', () => {
                    selectedRating = parseInt(star.dataset.rating);
                    updateRatingStars();
                    productRating.value = selectedRating;
                });
            });

            // 登出按钮
            logoutBtn.addEventListener('click', logout);

            // 滚动时导航栏效果
            window.addEventListener('scroll', () => {
                const navbar = document.getElementById('navbar');
                if (window.scrollY > 50) {
                    navbar.classList.add('shadow-md');
                    navbar.classList.remove('shadow-sm');
                } else {
                    navbar.classList.remove('shadow-md');
                    navbar.classList.add('shadow-sm');
                }
            });
        }

        // 处理表单提交
        async function handleFormSubmit(e) {
            e.preventDefault();
            
            // 表单验证
            if (!validateForm()) {
                return;
            }

            // 获取表单数据
            const formData = new FormData();
            formData.append('name', document.getElementById('productName').value);
            formData.append('price', parseFloat(document.getElementById('productPrice').value));
            formData.append('category', document.getElementById('productCategory').value);
            formData.append('description', document.getElementById('productDescription').value);
            formData.append('rating', parseFloat(productRating.value || 0));
            formData.append('reviews', parseInt(document.getElementById('productReviews').value || 0));
            formData.append('image', fileUpload.files[0]);

            try {
                // 显示加载状态
                const submitBtn = createProductForm.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 提交中...';

                // 发送请求
                const response = await fetch('http://192.168.10.124:8000/products/', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    },
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('创建商品失败');
                }

                // 显示成功消息并跳转
                showToast('商品创建成功！');
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1500);

            } catch (error) {
                console.error('Error creating product:', error);
                showToast('创建商品失败，请重试', 'error');
                
                // 恢复按钮状态
                const submitBtn = createProductForm.querySelector('button[type="submit"]');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '创建商品 <i class="fa fa-check ml-1"></i>';
            }
        }

        // 表单验证
        function validateForm() {
            let isValid = true;
            
            // 验证商品名称
            const nameInput = document.getElementById('productName');
            const nameError = document.getElementById('nameError');
            if (!nameInput.value.trim()) {
                nameError.classList.remove('hidden');
                isValid = false;
            } else {
                nameError.classList.add('hidden');
            }
            
            // 验证价格
            const priceInput = document.getElementById('productPrice');
            const priceError = document.getElementById('priceError');
            if (!priceInput.value || isNaN(priceInput.value) || parseFloat(priceInput.value) < 0) {
                priceError.classList.remove('hidden');
                isValid = false;
            } else {
                priceError.classList.add('hidden');
            }
            
            // 验证分类
            const categoryInput = document.getElementById('productCategory');
            const categoryError = document.getElementById('categoryError');
            if (!categoryInput.value) {
                categoryError.classList.remove('hidden');
                isValid = false;
            } else {
                categoryError.classList.add('hidden');
            }
            
            // 验证描述
            const descriptionInput = document.getElementById('productDescription');
            const descriptionError = document.getElementById('descriptionError');
            if (!descriptionInput.value.trim()) {
                descriptionError.classList.remove('hidden');
                isValid = false;
            } else {
                descriptionError.classList.add('hidden');
            }
            
            // 验证图片
            const imageError = document.getElementById('imageError');
            if (!fileUpload.files || fileUpload.files.length === 0) {
                imageError.classList.remove('hidden');
                isValid = false;
            } else {
                imageError.classList.add('hidden');
            }
            
            return isValid;
        }

        // 处理图片上传预览
        function handleImageUpload() {
            if (fileUpload.files && fileUpload.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreviewContainer.classList.remove('hidden');
                    
                    // 隐藏图片错误提示
                    document.getElementById('imageError').classList.add('hidden');
                }
                
                reader.readAsDataURL(fileUpload.files[0]);
            }
        }

        // 更新评分星星显示
        function updateRatingStars() {
            ratingStars.forEach(star => {
                const starRating = parseInt(star.dataset.rating);
                if (starRating <= selectedRating) {
                    star.classList.remove('text-gray-300');
                    star.classList.add('text-yellow-400');
                } else {
                    star.classList.remove('text-yellow-400');
                    star.classList.add('text-gray-300');
                }
            });
        }

        // 显示提示消息
        function showToast(message, type = 'success') {
            toastMessage.textContent = message;
            
            // 根据类型设置不同图标
            const icon = toast.querySelector('i');
            if (type === 'warning') {
                icon.className = 'fa fa-exclamation-circle text-yellow-400 mr-2';
            } else if (type === 'error') {
                icon.className = 'fa fa-times-circle text-red-500 mr-2';
            } else if (type === 'info') {
                icon.className = 'fa fa-info-circle text-blue-400 mr-2';
            } else {
                icon.className = 'fa fa-check-circle text-secondary mr-2';
            }
            
            // 显示提示
            toast.classList.remove('translate-y-20', 'opacity-0');
            toast.classList.add('translate-y-0', 'opacity-100');
            
            // 3秒后隐藏
            setTimeout(() => {
                toast.classList.remove('translate-y-0', 'opacity-100');
                toast.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }

        // 切换移动端菜单
        function toggleMobileMenu() {
            mobileMenu.classList.toggle('hidden');
        }

        // 检查用户认证状态
        async function checkAuth() {
            if (accessToken) {
                try {
                    const response = await fetch('http://192.168.10.124:8000/auth/user/', {
                        headers: { 'Authorization': `Bearer ${accessToken}` }
                    });
                    
                    if (response.ok) {
                        const userData = await response.json();
                        currentUser = userData;
                        updateUserUI();
                    } else {
                        // Token无效或过期，重定向到登录页
                        logout(true);
                    }
                } catch (error) {
                    console.error('Error checking auth:', error);
                    logout(true);
                }
            } else {
                // 未登录，重定向到登录页
                logout(true);
            }
        }

        // 从服务器加载购物车
        async function loadCart() {
            if (!accessToken) return;
            
            try {
                const response = await fetch('http://192.168.10.124:8000/cart/', {
                    headers: { 'Authorization': `Bearer ${accessToken}` }
                });
                
                if (response.ok) {
                    const cartData = await response.json();
                    cart = cartData.items || [];
                    updateCartCount();
                }
            } catch (error) {
                console.error('Error loading cart:', error);
            }
        }

        // 更新购物车数量
        function updateCartCount() {
            const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
            cartCount.textContent = totalItems;
        }

        // 更新用户UI
        function updateUserUI() {
            if (currentUser) {
                document.getElementById('auth-links').classList.add('hidden');
                userInfo.classList.remove('hidden');
                userInfo.querySelector('span').textContent = currentUser.username;
            } else {
                document.getElementById('auth-links').classList.remove('hidden');
                userInfo.classList.add('hidden');
            }
        }

        // 登出
        function logout(redirect = false) {
            localStorage.removeItem('access_token');
            accessToken = null;
            currentUser = null;
            cart = [];
            updateUserUI();
            updateCartCount();
            
            if (redirect) {
                showToast('请先登录管理员账号', 'info');
                setTimeout(() => window.location.href = 'login.html', 1500);
            } else {
                showToast('已成功登出');
                window.location.href = 'index.html';
            }
        }
    </script>
</body>
</html>
